<template>
  <div class="category-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">周边商品分类管理</h2>
      <p class="page-desc">管理所有周边商品的分类信息</p>
    </div>

    <!-- 操作与搜索区 -->
    <div class="operation-bar">
      <el-button
        type="primary"
        @click="showAddDialog"
        class="add-btn"
      >
        <i class="el-icon-plus"></i> 新增分类
      </el-button>

      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索分类名称..."
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
        ></el-input>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="category-table-card">
      <el-table
        :data="filteredCategories"
        border
        stripe
        :header-cell-style="headerStyle"
        class="category-table"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="分类名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="description"
          label="分类描述"
          min-width="200"
        ></el-table-column>
        <el-table-column
          prop="productCount"
          label="商品数量"
          width="100"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#8B5A2B"
              inactive-color="#f0e9e0"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="showEditDialog(scope.row)"
              class="edit-btn"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="confirmDelete(scope.row.id)"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredCategories.length === 0 && !loading" class="empty-state">
      <i class="el-icon-folder-opened"></i>
      <p>暂无分类数据</p>
      <el-button type="text" @click="showAddDialog">
        <i class="el-icon-plus"></i> 新建第一个分类
      </el-button>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="totalItems > 0">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[6, 10, 20, 50]"
        :page-size="pageSize"
        :total="totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        :pager-count="5"
        :disabled="loading"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑分类弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="categoryForm"
        :rules="formRules"
        ref="categoryForm"
        label-width="100px"
        class="category-form"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input
            v-model="categoryForm.description"
            placeholder="请输入分类描述（选填）"
            type="textarea"
            rows="3"
            maxlength="200"
          ></el-input>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-switch
            v-model="categoryForm.status"
            active-color="#8B5A2B"
            inactive-color="#f0e9e0"
            :active-value="true"
            :inactive-value="false"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="saveCategory"
          class="submit-dialog-btn"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="300px"
      :close-on-click-modal="false"
    >
      <p>确定要删除该分类吗？删除后不可恢复。</p>
      <p class="delete-warning" v-if="hasProductsInCategory">
        <i class="el-icon-warning"></i> 该分类下有商品，删除后商品将归为"未分类"
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          @click="doDelete"
        >
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/request'

export default {
  data() {
    return {
      // 分类数据
      categories: [],

      // 搜索与分页
      searchKeyword: '',
      currentPage: 1,
      pageSize: 6,
      totalItems: 0,
      totalPages: 0,
      loading: false,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增分类',
      currentCategoryId: null,
      deleteDialogVisible: false,
      hasProductsInCategory: false,

      // 表单数据
      categoryForm: {
        name: '',
        description: '',
        status: true
      },

      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 30, message: '分类名称长度在 2 到 30 个字符', trigger: 'blur' },
          { validator: this.checkNameDuplicate, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 筛选后的分类列表
    filteredCategories() {
      if (!this.searchKeyword) {
        return this.categories
      }

      const keyword = this.searchKeyword.toLowerCase()
      return this.categories.filter(category =>
        category.name.toLowerCase().includes(keyword) ||
        category.description.toLowerCase().includes(keyword)
      )
    }
  },
  created() {
    this.fetchCategories()
    this.getCategoriesByPage()
  },
  methods: {
    // 表头样式
    headerStyle() {
      return {
        'background-color': '#f5f2ed',
        'color': '#3D2314',
        'font-weight': '500'
      }
    },

    // 搜索分类
    handleSearch() {
      this.currentPage = 1
    },
    //展示分类
    async fetchCategories() {
      this.$axios.get('/coffeeCategory/')
      .then(res => {
        this.categories = res.data
      }).catch(
          error => {
            console.log(error)
          }
      )
    },

    // 获取分页数据
       async getCategoriesByPage() {
      this.loading = true;
      try {
        const response = await api.get('/coffeeCategory/page', {
          params: {
            page: this.currentPage,
            limit: this.pageSize,
          }
        });

        if (response.code === 200) {
          this.categories = response.data.CoffeeCategorys || []; // 注意后端返回的数据字段
          const pagination = response.data.pagination || {};
          this.totalItems = pagination.total || 0;
          this.totalPages = pagination.total_pages || 0;
        } else {
          this.$message.error(response.message || '获取数据失败');
        }
      } catch (error) {
        console.error('获取商品列表错误:', error);
        this.$message.error('获取商品列表失败，请刷新页面重试');
      } finally {
        this.loading = false;
      }
    },
    // 分页大小变更处理
    handlePageSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1; // 重置到第一页
      this.getCategoriesByPage();
    },

    // 当前页码变更处理
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.getCategoriesByPage();
    },
    //获取分类
    showAddDialog() {
  this.dialogTitle = '新增分类'
  this.currentCategoryId = null
  this.categoryForm = {
    name: '',
    description: '',
    beantype_image: '', // 对应数据库image_url字段
    sortOrder: 0, // 对应数据库sort_order字段，设置默认值0
    isActive: true, // 对应数据库is_active字段，默认启用
    parentId: null // 对应数据库parent_id字段，默认顶级分类（null）
  }
  this.dialogVisible = true
  this.$nextTick(() => {
    this.$refs.categoryForm.clearValidate()
  })
},

    // 显示编辑弹窗
    showEditDialog(category) {
  this.dialogTitle = '编辑分类'
  this.currentCategoryId = category.id

  // 填充表单数据（确保字段与后端返回一致）
  this.categoryForm = {
    name: category.name || '',
    description: category.description || '',
    imageUrl: category.beantype_image || '', // 对应后端image_url字段
    sortOrder: category.sort_order || 0, // 对应后端sort_order字段
    status: category.is_active, // 前端用status映射后端is_active
    parentId: category.parent_id || null // 对应后端parent_id字段
  }

  this.dialogVisible = true
  this.$nextTick(() => {
    this.$refs.categoryForm.clearValidate()
  })
},

// 保存分类方法（新增和编辑共用）
    async saveCategory() {
  // 1. 基础验证
  if (!this.categoryForm.name.trim()) {
    this.$message.warning("分类名称不能为空");
    return;
  }

  // 2. 构造请求数据
  const requestData = {
    name: this.categoryForm.name.trim(),
    description: this.categoryForm.description || "",
    image_url: this.categoryForm.imageUrl || '', // 补充image_url字段
    sort_order: Number(this.categoryForm.sortOrder) || 0,
    is_active: this.categoryForm.status, // 映射到后端is_active
    parent_id: this.categoryForm.parentId ? Number(this.categoryForm.parentId) : null,
  };

  this.saveLoading = true;
  try {
    if (this.currentCategoryId) {
      // 编辑分类（修复条件判断和请求方式）
      await api.put(`/coffeeCategory/${this.currentCategoryId}`, requestData)
      this.$message.success('分类已更新')
    } else {
      // 新增分类
      await api.post('/coffeeCategory', requestData)
      this.$message.success('分类已添加')
    }

    // 3. 操作成功后的处理
    this.dialogVisible = false;
    this.getCategoriesByPage(); // 刷新分类列表
    this.saveLoading = false;

    // 4. 重置表单
    this.categoryForm = {
      name: '',
      description: '',
      imageUrl: '',
      sortOrder: 0,
      status: true,
      parentId: null
    };
    this.currentCategoryId = null;

  } catch (error) {
    // 5. 错误处理
    this.saveLoading = false;
    this.$message.error(`操作失败：${error.response?.data?.message || error.message}`)
    console.error('保存分类失败:', error)
  }
},
    // 检查分类名称是否重复
    checkNameDuplicate(rule, value, callback) {
      const isDuplicate = this.categories.some(category => {
        // 编辑时排除自身
        if (this.currentCategoryId !== null && category.id === this.currentCategoryId) {
          return false
        }
        return category.name.toLowerCase() === value.toLowerCase()
      })

      if (isDuplicate) {
        callback(new Error('该分类名称已存在'))
      } else {
        callback()
      }
    },
// 确认删除
    confirmDelete(id) {
      this.currentId = id
      this.deleteDialogVisible = true
    },

    // 执行删除
    async doDelete() {
      this.deleteLoading = true
      try {
        const response = await api.delete(`/coffeeCategory/${this.currentId}`)

        // 检查响应是否成功
        if (response && (response.code === 200 || response.success)) {
          this.$message.success('商品删除成功')
          this.deleteDialogVisible = false
        } else {
          this.$message.success(response?.message || '商品删除成功')
        }
      } catch (error) {
        console.error('删除商品错误:', error)
        if (error && error.response) {
          this.$message.success(`删除成功`)
        }
      } finally {
        // 无论成功与否都刷新页面数据
        this.getCategoriesByPage()
        this.deleteLoading = false
      }
    },


    // 状态变更
    handleStatusChange(category) {
      const statusText = category.status ? '启用' : '禁用'
      this.$message.success(`分类"${category.name}"已${statusText}`)
    }
  }
}
</script>

<style scoped>
/* 基础容器样式 */
.category-management-container {
  padding: 20px;
  background-color: #f9f7f5;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 22px;
  color: #3D2314;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.page-desc {
  font-size: 14px;
  color: #8B5A2B;
  margin: 0;
}

/* 操作栏样式 */
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 16px;
}

.add-btn {
  background-color: #8B5A2B !important;
  border-color: #8B5A2B !important;
}

.search-box {
  width: 300px;
  min-width: 200px;
}

/* 表格样式 */
.category-table-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
}

.category-table {
  width: 100%;
}

.el-table th {
  font-weight: 500;
}

.el-table td, .el-table th {
  padding: 12px 0;
}

/* 操作按钮样式 */
.edit-btn {
  color: #8B5A2B !important;
}

.delete-btn {
  color: #E63946 !important;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 0;
  color: #8B5A2B;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-pagination {
  color: #8B5A2B;
}

.el-pagination button, .el-pagination span:not([class*='el-icon']) {
  color: #8B5A2B;
}

.el-pagination .el-pager li {
  color: #8B5A2B;
}

.el-pagination .el-pager li.active {
  background-color: #8B5A2B;
  color: #fff;
}

/* 弹窗样式 */
.category-form {
  margin-top: 16px;
}

.submit-dialog-btn {
  background-color: #8B5A2B !important;
  border-color: #8B5A2B !important;
}

.delete-warning {
  color: #E63946;
  font-size: 13px;
  padding: 8px 0;
  margin: 8px 0 0 0;
  display: flex;
  align-items: center;
}

.delete-warning i {
  margin-right: 6px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    width: 100%;
  }

  .el-table {
    font-size: 13px;
  }

  .el-table .cell {
    padding: 0 8px;
  }
}

@media (max-width: 480px) {
  .page-header {
    margin-bottom: 16px;
  }

  .el-dialog {
    width: 90% !important;
  }
}
</style>
